<template>
  <div class="flex flex-row w-1/1">
    <el-input v-model="code" @input="changeCode" placeholder="请输入验证码" :disabled="props.disabled">
      <template #prefix>
        <el-icon><Mug /></el-icon>
      </template>
    </el-input>
    <el-button @click="send" v-if="maxTime === nowTime" :disabled="props.disabled">发送验证码 </el-button>
    <el-button v-else-if="maxTime !== nowTime">{{ nowTime }}秒后重新发送</el-button>
  </div>
</template>

<script setup lang="ts">
import { sendCode, sendAccountCode } from "@/api/modules/account";
import { ref, onBeforeMount } from "vue";
import { ValidPhone } from "@/utils/eleValidate";
import { ElMessage } from "element-plus";

const maxTime = ref(60);
const nowTime = ref(maxTime.value);

interface Props {
  phone: string;
  code: any;
  sessionName: string;
  disabled?: boolean;
}

const emits = defineEmits(["update:code"]);

const code = ref("");

const props = withDefaults(defineProps<Props>(), {
  sessionName: "login_session",
  disabled: false
});

const setTime = () => {
  const codeTime = sessionStorage.getItem(props.sessionName);
  if (!codeTime) sessionStorage.setItem(props.sessionName, "60");
};

const timer = ref<NodeJS.Timer>();

const countTime = () => {
  nowTime.value--;
  timer.value = setInterval(() => {
    if (nowTime.value > 1) {
      nowTime.value--;
      sessionStorage.setItem(props.sessionName, `${nowTime.value}`);
    } else {
      nowTime.value = maxTime.value;
      sessionStorage.removeItem(props.sessionName);
      clearInterval(timer.value);
    }
  }, 1000);
};

const send = async () => {
  if (!ValidPhone(props.phone)) return ElMessage.error("手机号格式不正确");
  setTime();
  countTime();
  props.sessionName === "login_session" ? await sendCode(props.phone) : await sendAccountCode(props.phone);
  ElMessage.success("发送成功");
};

const changeCode = (val: any) => {
  emits("update:code", val);
};

onBeforeMount(() => {
  const nowCountTime = sessionStorage.getItem(props.sessionName);
  if (nowCountTime) {
    nowTime.value = parseInt(nowCountTime);
    if (nowTime.value !== maxTime.value) {
      countTime();
    }
  }
});
</script>

<style></style>
